#!/bin/bash

# 安装依赖
apt-get update
apt-get install -y python3 python3-pip iptables
mkdir -p ~/.pip
cat > ~/.pip/pip.conf << EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
EOF
pip3 install psutil flask flask-login

# 获取当前脚本所在目录的绝对路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# 创建必要的目录和文件
mkdir -p ${SCRIPT_DIR}/templates
chmod 755 ${SCRIPT_DIR}/templates
touch ${SCRIPT_DIR}/defender.log
chmod 666 ${SCRIPT_DIR}/defender.log

# 设置执行权限
chmod +x ${SCRIPT_DIR}/linux_defender.py

# 创建系统服务
cat > /etc/systemd/system/linux-defender.service << EOF
[Unit]
Description=Linux Defender Service
After=network.target

[Service]
ExecStart=/usr/bin/python3 ${SCRIPT_DIR}/linux_defender.py
WorkingDirectory=${SCRIPT_DIR}
Restart=always
User=root
StandardOutput=append:${SCRIPT_DIR}/defender.log
StandardError=append:${SCRIPT_DIR}/defender.log

[Install]
WantedBy=multi-user.target
EOF

# 重启服务
systemctl daemon-reload
systemctl restart linux-defender

# 等待服务启动
sleep 2

# 检查服务状态
systemctl status linux-defender 